package com.yjq.blog.article.controller;

import com.yjq.blog.article.service.CometService;
import com.yjq.blog.article.vo.CometReceiveVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/comet")
public class CometController {

    @Resource
    private CometService cometService;

    @GetMapping("/message")
    public void receiveMessage(@RequestParam("sessionId") String sessionId, HttpServletRequest req, HttpServletResponse resp) {
        if (StringUtils.isEmpty(sessionId)) {
            throw new IllegalArgumentException("请求参数异常, sessionId和data均不能为空");
        }
        log.info("sessionId: {}", sessionId);
        cometService.receiveMessage(sessionId, req, resp);
    }

    @PostMapping("/message")
    public boolean sendMessage(@RequestBody CometReceiveVO cometReceiveVO) {
        String sessionId = cometReceiveVO.getSessionId();
        String data = cometReceiveVO.getData();
        if (StringUtils.isEmpty(sessionId) || StringUtils.isEmpty(data)) {
            throw new IllegalArgumentException("请求参数异常, sessionId和data均不能为空");
        }
        log.info("sessionId: {}; data: {}", sessionId, data);
        cometService.sendMessage(sessionId, data);
        return true;
    }

}
